<template>
  <div class="content">
    <div class="list" v-for="(item, index) in list" :key="index">
      <div class="list_title">
        <img src="@/static/ship.png" alt="" />
        <span>{{ item.name }}</span>
      </div>
      <div class="list_text">
        <span>MMSI:</span>
        <span>{{ item.MMSI }}</span>
      </div>
      <div class="list_text">
        <span>时间:</span>
        <span>{{ item.date }}</span>
      </div>
      <div class="list_text">
        <span>地点:</span>
        <span>{{ item.address }}</span>
      </div>
      <div style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        ">
        <div class="wLeve">
          {{ item.type }}
        </div>
        <div class="listBtn">
          <i class="el-icon-thumb" style="margin-right: 10px">忽略</i>
          <i class="el-icon-error">结束</i>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { Place } from "@/utils/request.js";

interface WarningItem {
  name: string;
  MMSI: number;
  date: string;
  address: string;
  type: string;
  lon?: number;
  lat?: number;
  mmsi?: number;
  [key: string]: any;
}

// 声明全局类型
declare global {
  interface Window {
    T: any;
  }
}

const props = defineProps({
  map: Object
});

const emit = defineEmits(['showShip', 'queryShip']);

const placeValue = ref<any>(null); //1是册子 2是金塘
const current = ref(0);
const path = ref('');
const websock = ref<WebSocket | null>(null);
const intervalObj = ref<number | null>(null); //心跳定时器
const list = ref<WarningItem[]>([
  {
    name: "20231500123",
    MMSI: 0,
    date: "2023-03-10 14:57:27",
    address: "秀山-长白",
    type: "禁止驶入",
  },
]);
const isShow = ref(true);
const timer = ref<number | null>(null);
const autoplay = ref(true);
const searchMarker = ref(null);
const onChuan = ref(null);
const isCache = ref(false);
const shipMarker = ref(null);
const marker = ref(null);

/**
 * 心跳检测
 * @param websock
 * @param timeout 心跳间隔（单位毫秒）
 */
const HeartCheck = (websock: WebSocket, timeout: number) => {
  console.log("告警消息心跳");
  // 清除心跳
  if (intervalObj.value) clearInterval(intervalObj.value);
  intervalObj.value = window.setInterval(function () {
    // 这里发送一个心跳，后端收到后，返回一个心跳消息
    // message 表示发送的是消息 heart表示心跳 则data必须是ping
    websock.send("ping");
  }, timeout);
};

const websocketsend = () => {
  //数据发送
  // let msg=JSON.stringify(111111);
  // websock.value?.send(msg);
};

const websocketonopen = () => {
  console.log("告警消息websocket已打开");
};

const websocketonerror = (e: Event) => {
  console.log("告警消息websocket发生了错误", e);
};

const websocketclose = () => {
  console.log("告警消息websocket已关闭");
};

const websocketonmessage = (msg: MessageEvent) => {
  //数据接收
  //这里处理response
  if (msg) {
    if (msg.data && msg.data != "pong") {
      isShow.value = true;
      autoplay.value = true;
      let obj = JSON.parse(msg.data) as WarningItem;
      list.value.push(obj);
      
      if (isCache.value) {
        let str = JSON.stringify(list.value);
        localStorage.setItem("warnList", str);
      }
      
      // 数据超过二十条重置
      // if(list.value.length>=20){
      // 	current.value = 0;
      // 	list.value = [];
      // 	localStorage.removeItem('warnList');
      // }

      if (timer.value) clearTimeout(timer.value);
      hideWarn();
    }
  }
};

const chanSwiper = (e: { detail: { current: number } }) => {
  current.value = e.detail.current;
  if (current.value == list.value.length - 1) {
    autoplay.value = false;
  }
};

const hideWarn = () => {
  timer.value = window.setTimeout(() => {
    if (current.value == list.value.length - 1) {
      isShow.value = false;
      current.value = 0;
      list.value = [];
    }
  }, 60000);
};

const showShip = (item: WarningItem) => {
  if (!props.map || !item.lon || !item.lat) return;
  
  const T = window.T;
  props.map.panTo(new T.LngLat(item.lon, item.lat));
  onChuan.value = item;
  
  if (marker.value) {
    props.map.removeOverLay(marker.value);
  }

  let icon = new T.Icon({
    iconUrl: "http://116.148.229.186:81/images/posi.png",
    iconSize: new T.Point(25, 25),
    iconAnchor: new T.Point(12, 12),
  });
  
  //创建标注对象
  marker.value = new T.Marker(new T.LngLat(item.lon, item.lat), {
    icon: icon,
  });
  
  marker.value.addEventListener("click", function () {
    emit("showShip", item.mmsi);
  });
  
  //向地图上添加标注
  props.map.addOverLay(marker.value);
  emit("queryShip", item.mmsi);
};

// WebSocket获取数据
const initWebSocket = () => {
  if (typeof WebSocket == "undefined") {
    console.log("您的浏览器不支持WebSocket");
  } else {
    console.log("您的浏览器支持WebSocket");

    if (websock.value != null) {
      websock.value.close();
      websock.value = null;
    }
    
    websock.value = new WebSocket(path.value);
    websock.value.onmessage = websocketonmessage;
    websock.value.onopen = websocketonopen;
    websock.value.onerror = websocketonerror;
    websock.value.onclose = websocketclose;

    // 创建心跳对象
    HeartCheck(websock.value, 50000); // 设置间隔50秒的心跳
  }
};

//
const setWarnList = () => {
  let str = JSON.stringify(list.value);
  localStorage.setItem("warnList", str);
  isCache.value = true;
};

const stopCache = () => {
  isCache.value = false;
  localStorage.removeItem("warnList");
};

onMounted(() => {
  placeValue.value = Place;
  let num = new Date().getTime();
  // @ts-ignore - 假设$earlyurl在全局环境中已定义
  path.value = globalThis.$earlyurl + placeValue.value + "/" + num;
  initWebSocket();
});

onBeforeUnmount(() => {
  if (websock.value) {
    websock.value.onclose = null;
    websock.value.close();
  }
});
</script>

<style scoped>
.content {
  position: absolute;
  right: 60px;
  bottom: 30px;
  /* background: #000; */
  z-index: 999;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  overflow: hidden;
}

.list {
  width: 250px;
  /* height: 150px; */
  background-color: #ffffff;
  border-left: solid 5px red;
  padding: 10px;
  margin-bottom: 20px;
}

.list_title {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 10px;
}

.list_title>img {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}

.list_text {
  margin-bottom: 6px;
  display: flex;
}

.list_text>span:first-child {
  width: 60px;
  display: block;
}

.wLeve {
  padding: 4px 10px;
  background-color: red;
  border-radius: 6px;
  color: #ffffff;
}

.listBtn:hover {
  cursor: pointer;
}</style>